// 全局变量
let currentTab = 'quick';
let websocket = null;
let connectionStatus = 'disconnected';

// API基础URL
const API_BASE = '/api/v1';
const WS_BASE = `ws://${window.location.host}/api/v1/ws`;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 应用初始化
async function initializeApp() {
    console.log('🧪 初始化API测试工具...');
    
    // 设置事件监听器
    setupEventListeners();
    
    // 检查连接状态
    await checkConnection();
    
    console.log('✅ API测试工具初始化完成');
}

// 设置事件监听器
function setupEventListeners() {
    console.log('🔧 设置事件监听器...');
    
    // Tab切换事件监听器
    document.querySelectorAll('.nav-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.getAttribute('data-tab');
            console.log(`🖱️ 点击Tab按钮: ${tabName}`);
            switchTab(tabName);
        });
    });
    
    // 连接测试按钮
    const checkConnectionBtn = document.getElementById('checkConnectionBtn');
    if (checkConnectionBtn) {
        checkConnectionBtn.addEventListener('click', checkConnection);
    }
    
    // 快速测试按钮
    const runAllQuickTestsBtn = document.getElementById('runAllQuickTestsBtn');
    if (runAllQuickTestsBtn) {
        runAllQuickTestsBtn.addEventListener('click', runAllQuickTests);
    }
    
    // 测试按钮
    const testBasicConnectionBtn = document.getElementById('testBasicConnectionBtn');
    if (testBasicConnectionBtn) {
        testBasicConnectionBtn.addEventListener('click', testBasicConnection);
    }
    
    const testHealthCheckBtn = document.getElementById('testHealthCheckBtn');
    if (testHealthCheckBtn) {
        testHealthCheckBtn.addEventListener('click', testHealthCheck);
    }
    
    const testModelsListBtn = document.getElementById('testModelsListBtn');
    if (testModelsListBtn) {
        testModelsListBtn.addEventListener('click', testModelsList);
    }
    
    const testSubscriptionFlowBtn = document.getElementById('testSubscriptionFlowBtn');
    if (testSubscriptionFlowBtn) {
        testSubscriptionFlowBtn.addEventListener('click', testSubscriptionFlow);
    }
    
    // API测试刷新按钮
    const loadModelApiTestsBtn = document.getElementById('loadModelApiTestsBtn');
    if (loadModelApiTestsBtn) {
        loadModelApiTestsBtn.addEventListener('click', loadModelApiTests);
    }
    
    const loadSubscriptionApiTestsBtn = document.getElementById('loadSubscriptionApiTestsBtn');
    if (loadSubscriptionApiTestsBtn) {
        loadSubscriptionApiTestsBtn.addEventListener('click', loadSubscriptionApiTests);
    }
    
    const loadServerApiTestsBtn = document.getElementById('loadServerApiTestsBtn');
    if (loadServerApiTestsBtn) {
        loadServerApiTestsBtn.addEventListener('click', loadServerApiTests);
    }
    
    // WebSocket按钮
    const connectWebSocketBtn = document.getElementById('connectWebSocketBtn');
    if (connectWebSocketBtn) {
        connectWebSocketBtn.addEventListener('click', connectWebSocket);
    }
    
    const disconnectWebSocketBtn = document.getElementById('disconnectWebSocketBtn');
    if (disconnectWebSocketBtn) {
        disconnectWebSocketBtn.addEventListener('click', disconnectWebSocket);
    }
    
    const clearWebSocketLogBtn = document.getElementById('clearWebSocketLogBtn');
    if (clearWebSocketLogBtn) {
        clearWebSocketLogBtn.addEventListener('click', clearWebSocketLog);
    }
    
    // 批量测试按钮
    const runBatchTestsBtn = document.getElementById('runBatchTestsBtn');
    if (runBatchTestsBtn) {
        runBatchTestsBtn.addEventListener('click', runBatchTests);
    }
    
    console.log('✅ 事件监听器设置完成');
}

// 标签页切换
function switchTab(tabName) {
    console.log(`🔄 切换到Tab: ${tabName}`);
    
    try {
        // 隐藏所有标签页
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        
        // 移除所有标签按钮的激活状态
        document.querySelectorAll('.nav-tab').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // 显示目标标签页
        const targetTab = document.getElementById(`${tabName}-tab`);
        if (targetTab) {
            targetTab.classList.add('active');
            console.log(`✅ 显示标签页: ${targetTab.id}`);
        } else {
            console.error(`❌ 未找到标签页: ${tabName}-tab`);
        }
        
        // 激活对应的标签按钮
        const targetBtn = document.querySelector(`[data-tab="${tabName}"]`);
        if (targetBtn) {
            targetBtn.classList.add('active');
            console.log(`✅ 激活按钮: ${targetBtn.getAttribute('data-tab')}`);
        } else {
            console.error(`❌ 未找到按钮: data-tab="${tabName}"`);
        }
        
        currentTab = tabName;
        console.log(`✅ Tab切换完成: ${tabName}`);
        
    } catch (error) {
        console.error('❌ Tab切换失败:', error);
    }
    
    // 根据标签页加载对应数据
    switch(tabName) {
        case 'models':
            loadModelApiTests();
            break;
        case 'subscriptions':
            loadSubscriptionApiTests();
            break;
        case 'servers':
            loadServerApiTests();
            break;
        case 'websocket':
            updateWebSocketStatus();
            break;
        case 'batch':
            loadBatchTests();
            break;
    }
}

// 检查连接状态
async function checkConnection() {
    const statusElement = document.getElementById('connectionStatus');
    
    try {
        updateConnectionStatus(statusElement, 'checking', '检查连接...');
        
        const response = await fetch(`${API_BASE}/health/ping`);
        const data = await response.json();
        
        if (response.ok && data.status === 'ok') {
            updateConnectionStatus(statusElement, 'connected', '连接正常');
            connectionStatus = 'connected';
        } else {
            updateConnectionStatus(statusElement, 'disconnected', '连接异常');
            connectionStatus = 'disconnected';
        }
    } catch (error) {
        console.error('连接检查失败:', error);
        updateConnectionStatus(statusElement, 'disconnected', '连接失败');
        connectionStatus = 'disconnected';
    }
}

// 更新连接状态
function updateConnectionStatus(element, status, text) {
    const dot = element.querySelector('.status-dot');
    const textEl = element.querySelector('.status-text');
    
    // 移除所有状态类
    dot.classList.remove('connected', 'disconnected');
    
    // 添加新状态类
    if (status !== 'checking') {
        dot.classList.add(status);
    }
    
    textEl.textContent = text;
}

// 快速测试 - 运行所有测试
async function runAllQuickTests() {
    const btn = document.getElementById('runAllQuickTestsBtn');
    const originalText = btn.innerHTML;
    
    btn.disabled = true;
    btn.innerHTML = '🔄 运行中...';
    
    try {
        await testBasicConnection();
        await new Promise(resolve => setTimeout(resolve, 500));
        
        await testHealthCheck();
        await new Promise(resolve => setTimeout(resolve, 500));
        
        await testModelsList();
        await new Promise(resolve => setTimeout(resolve, 500));
        
        await testSubscriptionFlow();
        
        showNotification('所有快速测试完成', 'success');
    } catch (error) {
        console.error('快速测试失败:', error);
        showNotification('快速测试失败', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}

// 基础连接测试
async function testBasicConnection() {
    const resultContainer = document.getElementById('basicConnectionResult');
    resultContainer.innerHTML = '<div class="loading">测试中...</div>';
    
    try {
        const startTime = Date.now();
        const response = await fetch(`${API_BASE}/health/ping`);
        const endTime = Date.now();
        const data = await response.json();
        
        const result = {
            status: response.ok ? 'success' : 'error',
            statusCode: response.status,
            responseTime: endTime - startTime,
            data: data
        };
        
        resultContainer.innerHTML = renderTestResult('基础连接测试', result);
    } catch (error) {
        resultContainer.innerHTML = renderTestResult('基础连接测试', {
            status: 'error',
            error: error.message
        });
    }
}

// 健康检查测试
async function testHealthCheck() {
    const resultContainer = document.getElementById('healthCheckResult');
    resultContainer.innerHTML = '<div class="loading">测试中...</div>';
    
    try {
        const startTime = Date.now();
        const response = await fetch(`${API_BASE}/health/status`);
        const endTime = Date.now();
        const data = await response.json();
        
        const result = {
            status: response.ok ? 'success' : 'error',
            statusCode: response.status,
            responseTime: endTime - startTime,
            data: data
        };
        
        resultContainer.innerHTML = renderTestResult('健康检查测试', result);
    } catch (error) {
        resultContainer.innerHTML = renderTestResult('健康检查测试', {
            status: 'error',
            error: error.message
        });
    }
}

// 模型列表测试
async function testModelsList() {
    const resultContainer = document.getElementById('modelsListResult');
    resultContainer.innerHTML = '<div class="loading">测试中...</div>';
    
    try {
        const startTime = Date.now();
        const response = await fetch(`${API_BASE}/models`);
        const endTime = Date.now();
        const data = await response.json();
        
        const result = {
            status: response.ok ? 'success' : 'error',
            statusCode: response.status,
            responseTime: endTime - startTime,
            data: data,
            summary: `找到 ${data.total || 0} 个模型`
        };
        
        resultContainer.innerHTML = renderTestResult('模型列表测试', result);
    } catch (error) {
        resultContainer.innerHTML = renderTestResult('模型列表测试', {
            status: 'error',
            error: error.message
        });
    }
}

// 订阅功能测试
async function testSubscriptionFlow() {
    const resultContainer = document.getElementById('subscriptionFlowResult');
    resultContainer.innerHTML = '<div class="loading">测试中...</div>';
    
    try {
        // 测试获取订阅列表
        const startTime = Date.now();
        const response = await fetch(`${API_BASE}/subscriptions?client_id=test-client`);
        const endTime = Date.now();
        const data = await response.json();
        
        const result = {
            status: response.ok ? 'success' : 'error',
            statusCode: response.status,
            responseTime: endTime - startTime,
            data: data,
            summary: `找到 ${data.subscriptions?.length || 0} 个订阅`
        };
        
        resultContainer.innerHTML = renderTestResult('订阅功能测试', result);
    } catch (error) {
        resultContainer.innerHTML = renderTestResult('订阅功能测试', {
            status: 'error',
            error: error.message
        });
    }
}

// 渲染测试结果
function renderTestResult(testName, result) {
    const statusClass = result.status === 'success' ? 'success' : 'error';
    const statusIcon = result.status === 'success' ? '✅' : '❌';
    
    return `
        <div class="test-result ${statusClass}">
            <div class="result-header">
                <span class="result-icon">${statusIcon}</span>
                <span class="result-title">${testName}</span>
                ${result.responseTime ? `<span class="result-time">${result.responseTime}ms</span>` : ''}
            </div>
            
            ${result.statusCode ? `<div class="result-status">HTTP ${result.statusCode}</div>` : ''}
            ${result.summary ? `<div class="result-summary">${result.summary}</div>` : ''}
            ${result.error ? `<div class="result-error">错误: ${result.error}</div>` : ''}
            
            ${result.data ? `
                <details class="result-details">
                    <summary>查看详细数据</summary>
                    <pre class="result-data">${JSON.stringify(result.data, null, 2)}</pre>
                </details>
            ` : ''}
        </div>
    `;
}

// WebSocket相关功能
function connectWebSocket() {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        showNotification('WebSocket已连接', 'warning');
        return;
    }
    
    try {
        websocket = new WebSocket(WS_BASE);
        
        websocket.onopen = function(event) {
            addWebSocketLog('connected', '✅ WebSocket连接成功');
            updateWebSocketStatus('connected');
            showNotification('WebSocket连接成功', 'success');
        };
        
        websocket.onmessage = function(event) {
            addWebSocketLog('received', `📥 收到消息: ${event.data}`);
        };
        
        websocket.onclose = function(event) {
            addWebSocketLog('disconnected', `❌ WebSocket连接关闭 (${event.code})`);
            updateWebSocketStatus('disconnected');
        };
        
        websocket.onerror = function(error) {
            addWebSocketLog('error', `🚨 WebSocket错误: ${error}`);
            updateWebSocketStatus('disconnected');
            showNotification('WebSocket连接失败', 'error');
        };
        
        updateWebSocketStatus('connecting');
        addWebSocketLog('connecting', '🔄 正在连接WebSocket...');
        
    } catch (error) {
        console.error('WebSocket连接失败:', error);
        addWebSocketLog('error', `🚨 连接失败: ${error.message}`);
        showNotification('WebSocket连接失败', 'error');
    }
}

function disconnectWebSocket() {
    if (websocket) {
        websocket.close();
        websocket = null;
        addWebSocketLog('disconnected', '❌ 手动断开WebSocket连接');
        updateWebSocketStatus('disconnected');
        showNotification('WebSocket已断开', 'info');
    }
}

function updateWebSocketStatus(status = 'disconnected') {
    const statusElement = document.querySelector('.status-indicator');
    if (statusElement) {
        statusElement.className = `status-indicator ${status}`;
        
        const statusText = {
            'connected': '已连接',
            'connecting': '连接中...',
            'disconnected': '未连接'
        };
        
        statusElement.textContent = statusText[status] || '未知状态';
    }
}

function addWebSocketLog(type, message) {
    const logContainer = document.getElementById('websocketLog');
    if (!logContainer) return;
    
    // 如果是第一条日志，清除占位符
    if (logContainer.querySelector('.log-placeholder')) {
        logContainer.innerHTML = '';
    }
    
    const timestamp = new Date().toLocaleTimeString('zh-CN');
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;
    logEntry.innerHTML = `
        <div class="log-timestamp">[${timestamp}]</div>
        <div class="log-message">${message}</div>
    `;
    
    logContainer.appendChild(logEntry);
    logContainer.scrollTop = logContainer.scrollHeight;
}

function clearWebSocketLog() {
    const logContainer = document.getElementById('websocketLog');
    if (logContainer) {
        logContainer.innerHTML = '<div class="log-placeholder">WebSocket日志将显示在这里</div>';
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    const container = document.getElementById('notificationContainer');
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <span>${message}</span>
        <button class="notification-close">×</button>
    `;
    
    // 添加关闭按钮事件监听器
    const closeBtn = notification.querySelector('.notification-close');
    closeBtn.addEventListener('click', function() {
        notification.remove();
    });
    
    container.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 3000);
}

// ==================== 模型API测试功能 ====================

function loadModelApiTests() {
    console.log('加载模型API测试...');
    const container = document.getElementById('modelEndpoints');
    if (!container) return;

    container.innerHTML = `
        <div class="api-test-section">
            <h3>📊 模型API测试</h3>
            <div class="endpoint-grid">
                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method get">GET</span>
                        <span class="endpoint-path">/api/v1/models</span>
                    </div>
                    <p>获取所有可用模型列表</p>
                    <button class="btn btn-primary" onclick="testGetModels()">测试</button>
                    <div class="test-result" id="getModelsResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method get">GET</span>
                        <span class="endpoint-path">/api/v1/models/{id}</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="modelIdInput" placeholder="模型ID">
                    </div>
                    <button class="btn btn-primary" onclick="testGetModelDetail()">测试</button>
                    <div class="test-result" id="getModelDetailResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method get">GET</span>
                        <span class="endpoint-path">/api/v1/models/statistics</span>
                    </div>
                    <p>获取模型统计信息</p>
                    <button class="btn btn-primary" onclick="testModelStatistics()">测试</button>
                    <div class="test-result" id="modelStatisticsResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method post">POST</span>
                        <span class="endpoint-path">/api/v1/models</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="newModelName" placeholder="模型名称">
                        <input type="text" id="newModelVersion" placeholder="版本">
                        <select id="newModelType">
                            <option value="detection">目标检测</option>
                            <option value="classification">图像分类</option>
                            <option value="segmentation">图像分割</option>
                        </select>
                    </div>
                    <button class="btn btn-success" onclick="testCreateModel()">测试</button>
                    <div class="test-result" id="createModelResult"></div>
                </div>
            </div>
        </div>
    `;
}

// ==================== 订阅API测试功能 ====================

function loadSubscriptionApiTests() {
    console.log('加载订阅API测试...');
    const container = document.getElementById('subscriptionEndpoints');
    if (!container) return;

    container.innerHTML = `
        <div class="api-test-section">
            <h3>🔔 订阅API测试</h3>
            <div class="endpoint-grid">
                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method get">GET</span>
                        <span class="endpoint-path">/api/v1/subscriptions</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="clientIdFilter" placeholder="客户端ID (可选)">
                    </div>
                    <button class="btn btn-primary" onclick="testGetSubscriptions()">测试</button>
                    <div class="test-result" id="getSubscriptionsResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method post">POST</span>
                        <span class="endpoint-path">/api/v1/subscriptions</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="subClientId" placeholder="客户端ID" required>
                        <input type="text" id="subModelName" placeholder="模型名称" required>
                        <input type="text" id="subServerId" placeholder="服务器ID" required>
                        <input type="url" id="subCallbackUrl" placeholder="回调URL">
                    </div>
                    <button class="btn btn-success" onclick="testCreateSubscription()">测试</button>
                    <div class="test-result" id="createSubscriptionResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method delete">DELETE</span>
                        <span class="endpoint-path">/api/v1/subscriptions/{id}</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="deleteSubId" placeholder="订阅ID">
                    </div>
                    <button class="btn btn-danger" onclick="testDeleteSubscription()">测试</button>
                    <div class="test-result" id="deleteSubscriptionResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method get">GET</span>
                        <span class="endpoint-path">/api/v1/subscriptions/statistics</span>
                    </div>
                    <p>获取订阅统计信息</p>
                    <button class="btn btn-primary" onclick="testSubscriptionStatistics()">测试</button>
                    <div class="test-result" id="subscriptionStatisticsResult"></div>
                </div>
            </div>
        </div>
    `;
}

// ==================== 服务器API测试功能 ====================

function loadServerApiTests() {
    console.log('加载服务器API测试...');
    const container = document.getElementById('serverEndpoints');
    if (!container) return;

    container.innerHTML = `
        <div class="api-test-section">
            <h3>🖥️ 服务器API测试</h3>
            <div class="endpoint-grid">
                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method get">GET</span>
                        <span class="endpoint-path">/api/v1/servers</span>
                    </div>
                    <p>获取所有注册服务器列表</p>
                    <button class="btn btn-primary" onclick="testGetServers()">测试</button>
                    <div class="test-result" id="getServersResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method post">POST</span>
                        <span class="endpoint-path">/api/v1/servers</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="serverName" placeholder="服务器名称" required>
                        <input type="url" id="serverUrl" placeholder="服务器URL" required>
                        <input type="text" id="serverDesc" placeholder="描述 (可选)">
                    </div>
                    <button class="btn btn-success" onclick="testRegisterServer()">测试</button>
                    <div class="test-result" id="registerServerResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method post">POST</span>
                        <span class="endpoint-path">/api/v1/servers/{id}/test</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="testServerId" placeholder="服务器ID">
                    </div>
                    <button class="btn btn-warning" onclick="testServerConnection()">测试</button>
                    <div class="test-result" id="testServerConnectionResult"></div>
                </div>

                <div class="endpoint-card">
                    <div class="endpoint-header">
                        <span class="method delete">DELETE</span>
                        <span class="endpoint-path">/api/v1/servers/{id}</span>
                    </div>
                    <div class="form-group">
                        <input type="text" id="deleteServerId" placeholder="服务器ID">
                    </div>
                    <button class="btn btn-danger" onclick="testDeleteServer()">测试</button>
                    <div class="test-result" id="deleteServerResult"></div>
                </div>
            </div>
        </div>
    `;
}

// ==================== 批量测试功能 ====================

function loadBatchTests() {
    console.log('加载批量测试...');
    const container = document.getElementById('batchTestContainer');
    if (!container) return;

    container.innerHTML = `
        <div class="batch-test-section">
            <h3>🚀 批量测试</h3>

            <div class="batch-controls">
                <button class="btn btn-success" onclick="runAllTests()">🎯 运行所有测试</button>
                <button class="btn btn-warning" onclick="runCriticalTests()">⚡ 关键测试</button>
                <button class="btn btn-info" onclick="runPerformanceTests()">📊 性能测试</button>
                <button class="btn btn-secondary" onclick="clearBatchResults()">🗑️ 清空结果</button>
            </div>

            <div class="test-summary" id="testSummary">
                <div class="summary-card">
                    <div class="summary-label">总测试数</div>
                    <div class="summary-value" id="totalTests">0</div>
                </div>
                <div class="summary-card success">
                    <div class="summary-label">通过</div>
                    <div class="summary-value" id="passedTests">0</div>
                </div>
                <div class="summary-card error">
                    <div class="summary-label">失败</div>
                    <div class="summary-value" id="failedTests">0</div>
                </div>
                <div class="summary-card">
                    <div class="summary-label">耗时</div>
                    <div class="summary-value" id="totalTime">0ms</div>
                </div>
            </div>

            <div class="batch-log" id="batchLog">
                <div class="log-header">
                    <h4>测试日志</h4>
                    <button class="btn btn-sm btn-secondary" onclick="clearBatchLog()">清空日志</button>
                </div>
                <div class="log-content" id="batchLogContent">
                    <div class="log-placeholder">批量测试日志将显示在这里...</div>
                </div>
            </div>
        </div>
    `;
}
